package find.prj.prog;

import java.awt.Desktop;
import java.awt.EventQueue;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.JScrollPane;
import javax.swing.JButton;
import javax.swing.JEditorPane;
import javax.swing.event.HyperlinkEvent;
import javax.swing.event.HyperlinkListener;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class URLTester {

	private JFrame frmUrlRssTester;
	private JTextField txtURL;
	private JEditorPane pane;

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					URLTester window = new URLTester();
					window.frmUrlRssTester.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the application.
	 */
	public URLTester() {
		initialize();
	}

	/**
	 * Initialize the contents of the frame.
	 */
	private void initialize() {
		frmUrlRssTester = new JFrame();
		frmUrlRssTester.setTitle("RSS Reader");
		frmUrlRssTester.setBounds(100, 100, 665, 473);
		frmUrlRssTester.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frmUrlRssTester.getContentPane().setLayout(null);
		frmUrlRssTester.setResizable(false);
		
		JLabel lblRssFeedLink = new JLabel("RSS Feed Link");
		lblRssFeedLink.setBounds(10, 11, 150, 14);
		frmUrlRssTester.getContentPane().add(lblRssFeedLink);
		
		txtURL = new JTextField();
		txtURL.setText("http://www.pravda.com.ua/rss/");
		txtURL.setBounds(10, 36, 531, 20);
		frmUrlRssTester.getContentPane().add(txtURL);
		txtURL.setColumns(10);
		
		JButton btnRetrieve = new JButton("Retrieve");
		btnRetrieve.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				Document xmldoc = null;
				try {
					xmldoc = getXmlDocument(txtURL.getText());
				} catch (MalformedURLException e) {
					JOptionPane.showMessageDialog(frmUrlRssTester, "This is not a valid URL", "Error", 0);
					return;
				} catch (SAXException e) {
					JOptionPane.showMessageDialog(frmUrlRssTester, "This URL does not contain XML file", "Error", 0);
					return;
				}
				if (xmldoc == null)
					return;
				if (xmldoc.getDocumentElement().getNodeName().toLowerCase() == "rss") {
					
					NodeList items = xmldoc.getElementsByTagName("item");
					String paneText = "";
					for (int i=0; i< items.getLength(); i++) {
						Node item = items.item(i);
						if (item.getNodeType() == Node.ELEMENT_NODE)
							paneText += getRssItemString(item);
		
					}
					pane.setText(paneText);
				}
				else
					JOptionPane.showMessageDialog(frmUrlRssTester, "This URL does not contain RSS Feed", "Error", 0);
			}
		});
		btnRetrieve.setBounds(550, 33, 98, 26);
		frmUrlRssTester.getContentPane().add(btnRetrieve);
		
		JScrollPane scrollPane = new JScrollPane();
		scrollPane.setBounds(10, 67, 640, 370);
		frmUrlRssTester.getContentPane().add(scrollPane);
		
		pane = new JEditorPane();
		pane.setContentType("text/html");
		pane.setEditable(false);
		scrollPane.setViewportView(pane);
		pane.addHyperlinkListener(new HyperlinkListener() {
		    
			@Override
			public void hyperlinkUpdate(HyperlinkEvent arg0) {
		        if(arg0.getEventType() == HyperlinkEvent.EventType.ACTIVATED)
		        	if(Desktop.isDesktopSupported())
						try {
							Desktop.getDesktop().browse(arg0.getURL().toURI());
						} catch (IOException e) {
							e.printStackTrace();
						} catch (URISyntaxException e) {
							e.printStackTrace();
						}
			}
		});
	}
	
	private Document getXmlDocument (String urlString) throws SAXException, MalformedURLException {
		HttpURLConnection httpCon = null;
		Document xmldoc = null;
		try {
			URL url = new URL(urlString);
			httpCon = (HttpURLConnection)url.openConnection();
			httpCon.setRequestMethod("GET");
			httpCon.setRequestProperty("Content-Type", "application/rss+xml");
			DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
			DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
			xmldoc = dBuilder.parse(new InputSource(new BufferedReader(new InputStreamReader(httpCon.getInputStream()))));
		}
		catch (IOException e) {
			e.printStackTrace();
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		} 
		finally {
			if(httpCon != null)
				httpCon.disconnect(); 
	    }
		return xmldoc; 
	}
	
	private String getRssItemString(Node item) {
		String result="";
		result += "<h2><a href=\"" + ((Element) item).getElementsByTagName("link").item(0).getTextContent() + "\">" +
				((Element) item).getElementsByTagName("title").item(0).getTextContent() + "</a></h2>\n";
		
		String description = ((Element) item).getElementsByTagName("description").item(0).getTextContent();
		description = description.replaceAll("\\<.+?\\>", "");
		
		result += "\n" + description + "\n\n";
		return result;
	}
}
